package com.potato369.cryptEureka.service.impl;

import com.potato369.cryptEureka.domain.Brand;
import com.potato369.cryptEureka.repository.BrandRepository;
import com.potato369.cryptEureka.service.BrandService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class BrandServiceImpl implements BrandService {

    private BrandRepository repository;

    @Autowired
    public void setRepository(BrandRepository repository) {
        this.repository = repository;
    }

    @Override
    public List<Brand> listAllBrand() {
        return this.repository.findAll();
    }

    @Override
    public int createBrand(Brand brand) {
        Brand result = this.repository.save(brand);
        if (Objects.isNull(result)) {
            return 0;
        }
        return 1;
    }

    @Override
    public int updateBrand(Long id, Brand brand) {
        Brand brandTemp = new Brand();
        brandTemp.setId(id);
        BeanUtils.copyProperties(brand, brandTemp);
        Brand result = this.repository.saveAndFlush(brandTemp);
        if (Objects.isNull(result)) {
            return 0;
        }
        return 1;
    }

    @Override
    public int deleteBrand(Long id) {
        this.repository.deleteById(id);
        Brand result = this.repository.findById(id).orElse(null);
        if (Objects.isNull(result)) {
            return 1;
        }
        return 0;
    }

    @Override
    public Page<Brand> listBrand(int pageNum, int pageSize) {
    	Sort sort = new Sort(Sort.Direction.ASC, "sort");
    	Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        return this.repository.findAll(pageable);
    }

    @Override
    public Brand getBrand(Long id) {
        return this.repository.findById(id).orElse(null);
    }
}
